// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const path = require('path');
const fs = require('fs');
const os = require('os')
function activate(context) {
  // 注册一个命令，用于打开 AMIS 编辑器
  let disposable = vscode.commands.registerCommand(
    'vscode-amis-editor.openEditor',
    () => {
      // 获取当前活动的编辑器
      const activeEditor = vscode.window.activeTextEditor;
      // 如果没有活动编辑器或者活动编辑器不是 JSON 文件，则提示用户打开 JSON 文件
      if (!activeEditor || !activeEditor.document.fileName.endsWith('.json')) {
        vscode.window?.showErrorMessage?.('Please open a JSON file first');
        return;
      }

      const panel = vscode.window.createWebviewPanel(
        'amisEditor',
        'AMIS Editor',
        vscode.ViewColumn.One,
        {
          enableScripts: true,
          retainContextWhenHidden: true,
          localResourceRoots: [
            vscode.Uri.file(path.join(context.extensionPath, 'media')),
          ],
        }
      );

      const filePath = activeEditor.document.uri.fsPath;
      const fileContent = activeEditor.document.getText();

      // 获取 AMIS 编辑器资源
      const amisEditorHtml = getWebviewContent(
        context,
        panel.webview,
        fileContent
      );

      panel.webview.html = amisEditorHtml;

      // 处理从 Webview 传来的消息
      panel.webview.onDidReceiveMessage(
        (message) => {
          switch (message.command) {
            case 'save':
              saveFile(filePath, message.data);
              return;
            case 'alert':
              vscode.window.showErrorMessage(message.text);
              return;
          }
        },
        undefined,
        context.subscriptions
      );

      // 监听文档变化
      const watcher = vscode.workspace.createFileSystemWatcher(filePath);
      watcher.onDidChange((uri) => {
        if (uri.fsPath === filePath) {
          const content = fs.readFileSync(filePath, 'utf-8');
          panel.webview.postMessage({ command: 'update', content });
        }
      });
      setTimeout(() => {
        panel.webview.postMessage({ command: 'update', content: fileContent });
      }, 10000);
      setTimeout(() => {
        panel.webview.postMessage({ command: 'openDevTools' });
      }, 1000);
      panel.onDidDispose(() => {
        watcher.dispose();
      });
    }
  );

  context.subscriptions.push(disposable);
}

function saveFile(filePath, content) {
  fs.writeFileSync(filePath, content, 'utf-8');
}

function getWebviewContent(context) {
  // 加载 AMIS 编辑器资源
  const htmlPath = vscode.Uri.file(
    path.join(context.extensionPath, '/amis-editor-vscode/dist/index.html')
  );
  const loadHtmlPath = os.platform() == 'win32' ?htmlPath.fsPath : htmlPath.path
  const content = fs.readFileSync(loadHtmlPath, 'utf-8');
  return content.toString();
}
function deactivate() {}

module.exports = {
  activate,
  deactivate,
};
